<template>
    <xt-card>
        <div class="opt-btn">
            <el-button type="primary" size="mini"
                :loading="state.saveLoading"
                :disabled="state.saveLoading"
                @click="submitForm()">保存</el-button>
        </div>
        <el-tabs>
            <el-tab-pane>
                <template #label>
                <span>基础信息</span>
                </template>
                <el-form :model="state.formData" :rules="rules" ref="state.formData" label-width="100px">
                    <el-form-item label="文章标题" prop="artTitle">
                        <el-input v-model="state.formData.artTitle"></el-input>
                    </el-form-item>
                    <el-form-item label="文章分类" prop="artC">
                        <el-cascader
                            v-model="state.formData.artCatValue"
                            :options="state.catOptions"
                            :props='{
                                value: "id",
                                label: "acName"
                            }'
                            @change="cHandleChange" >
                            <template #default="{ node, data }">
                                <span>{{ data.acName }}</span>
                                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
                            </template>
                        </el-cascader>
                    </el-form-item>
                    <el-form-item label="发布时间" prop="artPublishTime">
                        <el-date-picker type="datetime"
                            placeholder="选择发布时间"
                            :shortcuts="shortcuts"
                            format="YYYY-MM-DD HH:mm:ss"
                            value-format="YYYY-MM-DD HH:mm:ss"
                            v-model="state.formData.artPublishTime"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="封面图">
                        <el-upload
                            class="avatar-uploader"
                            :action="state.uploadUrl"
                            :show-file-list="false"
                            auto-upload
                            :headers="state.uploadHeaders"
                            :on-success="handleCoverSuccess"
                            :on-error="handleCoverError"
                            :before-upload="beforeCoverUpload">
                            <img class="avatar" 
                                v-if="state.formData.artCoverImage" 
                                :src="state.formData.artCoverImage" />
                                <el-icon v-else :size="80">
                                    <upload-filled :size="80"/>
                                </el-icon>
                        </el-upload>
                    </el-form-item>
                    <el-form-item label="文章状态" prop="artStatus">
                        <el-select v-model="state.formData.artStatus" placeholder="请选择状态">
                            <el-option label="正常" :value="0"></el-option>
                            <el-option label="审核中" :value="1"></el-option>
                            <el-option label="审核失败" :value="2"></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="首页置顶" prop="artHometop">
                        <el-radio v-model="state.formData.artHometop" :label="0">否</el-radio>
                        <el-radio v-model="state.formData.artHometop" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item label="是否推荐" prop="artRecommended">
                        <el-radio v-model="state.formData.artRecommended" :label="0">否</el-radio>
                        <el-radio v-model="state.formData.artRecommended" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item label="是否原创" prop="artOriginal">
                        <el-radio v-model="state.formData.artOriginal" :label="0">否</el-radio>
                        <el-radio v-model="state.formData.artOriginal" :label="1">是</el-radio>
                    </el-form-item>
                    <el-form-item label="文章来源" prop="artInfourl" v-if="state.formData.artOriginal==0">
                        <el-input v-model="state.formData.artInfourl"></el-input>
                    </el-form-item>
                    <el-form-item label="开启评论" prop="artComment">
                        <el-radio v-model="state.formData.artComment" :label="0">否</el-radio>
                        <el-radio v-model="state.formData.artComment" :label="1">是</el-radio>
                    </el-form-item>
                </el-form>
            </el-tab-pane>

            <el-tab-pane>
                <template #label>
                <span>富文本内容</span>
                </template>
                <xt-tinymce v-model="state.formData.artHtml"/>
            </el-tab-pane>

            <el-tab-pane>
                <template #label>
                <span>内容Markdown</span>
                </template>
                <v-md-editor v-model="state.formData.artMarkdown" height="600px"></v-md-editor>
            </el-tab-pane>

            <el-tab-pane>
                <template #label>
                <span>SEO信息</span>
                </template>
                <el-form :inline="true" :model="state.analysisForm">
                    <el-form-item label="关键词: ">
                        <el-input v-model="state.analysisForm.keywordSize" size="small" />
                    </el-form-item>
                    <el-form-item label="摘要: ">
                        <el-input v-model="state.analysisForm.summarySize" size="small" />
                    </el-form-item>
                    <el-form-item label="短语: ">
                        <el-input v-model="state.analysisForm.phraseSize" size="small" />
                    </el-form-item>
                    <el-form-item label="词语: ">
                        <el-input v-model="state.analysisForm.wordSize" size="small" />
                    </el-form-item>
                    <el-form-item>
                        <el-button type="success" size="small" @click="analysisClick"
                            :loading="state.analysisLoading"
                            :disabled="state.analysisLoading">智能解析</el-button>
                    </el-form-item>
                </el-form>
                <el-card shadow="always">
                    <template #header>
                        <div class="card-header">
                        <span>关键词</span>
                            <el-button class="button" type="text" @click="analysisSelectClick(0, '智能解析 - 关键词选择')">选择</el-button>
                        </div>
                    </template>
                    <el-input type="textarea" :rows="4" v-model="state.formData.artKeywords" ></el-input>
                </el-card>
                <el-divider></el-divider>
                <el-card shadow="always">
                    <template #header>
                        <div class="card-header">
                        <span>描述：</span>
                        <el-button class="button" type="text" @click="analysisSelectClick(1, '智能解析 - 描述选择')">选择</el-button>
                        </div>
                    </template>
                    <el-input type="textarea" :rows="4" v-model="state.formData.artDescription"></el-input>
                </el-card>
            </el-tab-pane>
        </el-tabs>

        <el-dialog
            :title="state.analysisDialogTitle"
            v-model="state.analysisDialogVisible"
            width="50%"
            :before-close="()=> state.analysisDialogVisible = false">
            <el-tabs type="border-card">
                <el-tab-pane>
                    <template #label>
                        关键词
                    </template>
                    <div v-if="state.analysisResult.keywords">
                        <el-checkbox-group v-model="state.analysisResult.keywordSelect">
                            <el-checkbox :label="item" :key="index"
                                v-for="(item, index) in state.analysisResult.keywords"></el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div v-else>
                        未分析出关键词
                    </div>
                </el-tab-pane>
                <el-tab-pane>
                    <template #label>
                        摘要
                    </template>
                    <div v-if="state.analysisResult.summary">
                        <el-checkbox-group v-model="state.analysisResult.summarySelect">
                            <el-checkbox :label="item" :key="index"
                                v-for="(item, index) in state.analysisResult.summary"></el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div v-else>
                        未分析出摘要
                    </div>
                </el-tab-pane>
                <el-tab-pane>
                    <template #label>
                        短语
                    </template>
                    <div v-if="state.analysisResult.phrases">
                        <el-checkbox-group v-model="state.analysisResult.phraseSelect">
                            <el-checkbox :label="item" :key="index"
                                v-for="(item, index) in state.analysisResult.phrases"></el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div v-else>
                        未分析出短语
                    </div>
                </el-tab-pane>
                <el-tab-pane>
                    <template #label>
                        词语
                    </template>
                    <div v-if="state.analysisResult.words">
                        <el-checkbox-group v-model="state.analysisResult.wordSelect">
                            <el-checkbox :label="item.text" :key="index"
                                v-for="(item, index) in state.analysisResult.words"></el-checkbox>
                        </el-checkbox-group>
                    </div>
                    <div v-else>
                        未分析出词语
                    </div>
                </el-tab-pane>
            </el-tabs>
            <template #footer>
                <span class="dialog-footer">
                <el-button @click="()=> state.analysisDialogVisible = false">取 消</el-button>
                <el-button type="primary" @click="analysisDialogClick">确 定</el-button>
                </span>
            </template>
        </el-dialog>
    </xt-card>
</template>
<script setup >
    import { useRoute } from 'vue-router'
    import { reactive, ref } from 'vue';
    import { onMounted } from 'vue';
    import { request } from "@/utils/request";
    import { ElMessage } from 'element-plus'
    import store from '@/store'
    import { BASE_URL, TOKEN_NAME } from '@/config/setting.config.js'
    import { UploadFilled } from '@element-plus/icons-vue'
    
    const route = useRoute();

    const props = defineProps({
        params: {}
    })
    
    let uploadHeaders = {};
    uploadHeaders[TOKEN_NAME] = store.getters['user/getToken'];
    let state = reactive({
        uploadUrl: BASE_URL + "/file/singleUpload",
        uploadHeaders: uploadHeaders,
        saveLoading: false,
        formData: {
            artCatValue: []
        },
        catOptions: [],

        analysisLoading: false,
        analysisForm: {
            keywordSize: 20,
            summarySize: 10,
            phraseSize: 20,
            wordSize: 20
        },
        analysisResult: {
            keywords: [],
            keywordSelect: [],
            summary: [],
            summarySelect: [],
            phrases: [],
            phraseSelect:[],
            words:[],
            wordSelect:[],
        },

        analysisDialogTitle: '',
        analysisDialogSelect: 0, //0选择关键词 1选择描述
        analysisDialogVisible: false,

    });
    let rules = reactive({});
    
    onMounted(() => {
        loadData();
    })

    let submitForm = () => {
        submitData();
        // this.$refs[state.formData].validate((valid) => {
        //     if (valid) {
        //         submitData();
        //     } else {
        //         return false
        //     }
        // })
    }
    let handleCoverSuccess = (res, file)  => {
        state.formData.artCoverImage = res.data;
        if(res.code == 200) {
            ElMessage.success({
                message: '上传成功',
                type: res.msg,
            })
        }else {
            ElMessage.error("上传失败: " + res.msg)
        }
    }
    let handleCoverError = (err, file, fileList) => {
        console.log('handleCoverSuccess.err', err);
        console.log('handleCoverSuccess.file', file);
        console.log('handleCoverSuccess.fileList', fileList);
        ElMessage.error("上传失败: " + err)
    }
    let beforeCoverUpload = (file) => {
        // const isJPG = file.type === 'image/jpeg'
        // const isLt2M = file.size / 1024 / 1024 < 2
        // if (!isJPG) {
        //   this.$message.error('上传头像图片只能是 JPG 格式!')
        // }
        // if (!isLt2M) {
        //   this.$message.error('上传头像图片大小不能超过 2MB!')
        // }
        return true;
    }
    let cHandleChange = (val) => {
        let artCidPath = '';
        for(let i = 0; i < val.length; i ++) {
            artCidPath += (i>0?'/':'') + val[i];
        }
        state.formData.artCidPath = artCidPath;
        state.formData.artCid = val[val.length - 1];
    }
    let analysisClick = () => {
        state.analysisForm.content = state.formData.artHtml;
        state.analysisLoading = true;
        request({
            url: '/nlp/analysisContent',
            method: 'post',
            data: state.analysisForm
        }).then(function (res) {
            state.analysisLoading = false;
            res.data.keywordSelect = [];
            res.data.summarySelect = [];
            res.data.phraseSelect = [];
            res.data.wordSelect = [];
            state.analysisResult = res.data;

            analysisSelectClick(0, '智能解析 - 关键词选择')
            
        }).catch(function (error) {
            state.analysisLoading = false;
            console.log('失败', error);
        });
    }

    let analysisSelectClick = (analysisDialogSelect, analysisDialogTitle) => {
        state.analysisDialogSelect = analysisDialogSelect;
        state.analysisDialogTitle = analysisDialogTitle;
        state.analysisDialogVisible = true;
        state.analysisResult.keywordSelect = [];
        state.analysisResult.summarySelect = [];
        state.analysisResult.phraseSelect = [];
        state.analysisResult.wordSelect = [];
    }

    let analysisDialogClick = () => {
        let select = state.analysisResult.keywordSelect
            .concat(state.analysisResult.summarySelect)
            .concat(state.analysisResult.phraseSelect)
            .concat(state.analysisResult.wordSelect);
        
        if(state.analysisDialogSelect == 0){
            state.formData.artKeywords = select.join(' ');
        }else{
            state.formData.artDescription = select.join(',');
        }
        state.analysisDialogVisible = false;
    }

    let submitData = () => {
        state.saveLoading = true;
        request({
            url: '/article/addOrUpdate',
            method: 'post',
            data: state.formData
        }).then(function (res) {
            state.saveLoading = false;
            if(res.code == 200) {
                ElMessage.success({
                    message: res.msg,
                    type: 'success',
                })
                route.query.id = res.data.id;
                loadDetail();
            }else {
                ElMessage.error(res.msg)
            }
            
        }).catch(function (error) {
            state.saveLoading = false;
            console.log('失败', error);
        });
   }

    let loadData = () => {
        loadDetail();
        loadCat();
    }

    let loadDetail = () => {
        if(!route.query.id) {
            return;
        }
        request({
            url: '/article/detail',
            method: 'get',
            params: {
                id: route.query.id
            }
        }).then(function (res) {
            if(res.data.artCidPath) {
                res.data.artCatValue = res.data.artCidPath.split('/');
            }
            state.formData = res.data;
        }).catch(function (error) {
            console.log('失败', error);
        });
    }
    let loadCat = () => {
        request({
            url: '/artcat/list',
            method: 'get',
        }).then(function (res) {
            state.catOptions = res.data;
        }).catch(function (error) {
            console.log('失败', error);
        });
    }
</script>

<style scoped>
    .main-context {
        padding: 0 20px;
        height: 100%;
    }
    .opt-btn {
        padding: 5px 0;
    }
    .avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
  }
  .avatar-uploader .el-upload:hover {
    border-color: #409eff;
  }
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
  }
  .avatar {
    width: 178px;
    height: 178px;
    display: block;
  }

  .card-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
  }
</style>